# Create your views here.
import datetime
import json

from django.http import HttpResponse

from Admin.models import Analytics
from Baby.models import Users
from Common.decorators import method, check_token, check_body
from Common.logger import app_log
from Common.response import resp
from NICU2HOME.configs import feedback


@method(['GET'])
def health_check(request):
    try:
        return HttpResponse("server is running\r\n")
    except Exception as e:
        app_log.exception(e)
        return HttpResponse("server is not works\r\n")


@method(['GET'])
def upgrade(request):
    try:
        android_version = '5.0.0'
        ios_version = '5.0.0.0'
        client = request.META.get("HTTP_X_CLIENT")
        app_version = request.META.get("HTTP_X_APP_VERSION")
        if client:
            if 'android' in client.lower():
                return resp(code=107, data='Upgrade required - android')
            if 'ios' in client.lower():
                return resp(code=107, data='Upgrade required - ios', )

        return resp(code=107, data='Upgrade required', )

    except Exception as e:
        app_log.exception(e)
        return HttpResponse("server is not works\r\n")


@method(['GET'])
def faq(request):
    try:
        return resp(0, feedback)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@method(['POST'])
@check_token()
@check_body(['client', 'screen_action', 'event_details'])
def analytics(request):
    try:
        ret = {}
        post_param = json.loads(request.body)
        userid = None
        if 'user_id' in post_param:
            userid = post_param['user_id']
            user = Users.objects.filter(id=userid).first()
            if not user:
                app_log.info(f'user not exist:{userid}')
        record = Analytics.objects.create(
            user_id=userid,
            screen_name=post_param['screen_name'],
            screen_action=post_param['screen_action'],
            client=post_param['client'],
            event_details=post_param['event_details'],
            application_version=post_param['application_version'],
            clientos=post_param['clientOS'],
            clientmodel=post_param['clientModel'],
            ip_address=request.META['REMOTE_ADDR'],
        )
        record.save()

        return resp(0, ret)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))
